<template>
  <c-form :inline="true" :form="form"></c-form>
  <el-dialog
      title="选择监听器"
      v-model="visible"
      width="800px"
      append-to-body
      destroy-on-close
  >
    <c-listeners-choose ref="listenersRef" :listenersData="listenersData" :listenersListByElement="listenersListByElement"></c-listeners-choose>
    <template #footer>
    <span class="dialog-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitListeners">确 定</el-button>
    </span>
    </template>
  </el-dialog>
</template>

<script>
import {mapActions, mapState} from "vuex";
import Form from "@/components/Form";
import {userListeners} from "@/components/bpmn/components/bpmnPropertiesPanel/forms";
import ListenersChoose from "./ListenersComponents/ListenersChoose.vue";

export default {
  name: "UserTask_Listeners",
  components: {
    "c-form": Form,
    "c-listeners-choose": ListenersChoose
  },
  data() {
    return {
      form: userListeners.call(this),
      visible: false,
      listenersData: [],
      businessObj: null
    }
  },
  computed: {
    ...mapState({
      listenersList: state => state.flowDesignStore.listenersList,
    }),
    listenersListByElement(){
      const type = this.businessObj?.$type;
      if(type === "bpmn:Process"){
        return this.listenersList && this.listenersList.slice(0,2);
      }else if(type === "bpmn:UserTask"){
        return this.listenersList && this.listenersList.slice(1,3);
      }else{
        return this.listenersList && [this.listenersList[1]];
      }
    },
    formatListenersList() {
      const obj = {};
      this.listenersList.forEach(item => {
        item.options.forEach(opt => {
          obj[opt.id] = opt
        })
      })
      return obj;
    }
  },
  methods: {
    ...mapActions("flowDesignStore", ["getListenersList"]),
    // 数据初始化
    async initData() {
      let listenersList = this.listenersList;
      if (!listenersList) {
        const rst = await this.getListenersList();
        if (!rst.status) {
          this.$message({
            type: "warning",
            message: rst.message,
          });
        } else {
          listenersList = rst.data;
        }
      }
      this.form.items.listeners.options = listenersList;
    },

    // 数据回填
    dataReset() {
      this.listenersDataReset();
    },

    listenersDialogDataReset(){
      let listenerIds = this.businessObj.listenerIds;
      const eventTypeMap = {
        "activiti:EventListener": "EVENT",
        "activiti:ExecutionListener": "EXECUTION",
        "activiti:TaskListener": "TASK"
      };
      this.visible = true;
      if(listenerIds){
        listenerIds = listenerIds.split(",");
        const listeners = this.businessObj.extensionElements.values;
        this.listenersData = listenerIds.map((item, index) => ({
          key: new Date().getTime() + "_" + index,
          eventType: eventTypeMap[listeners[index].$type],
          eventId: (listeners[index].event || listeners[index].events).split(","),
          listenerId: listenerIds[index]
        }));
        console.log(this.listenersData);
      }else{
        this.listenersData = [];
      }
    },

    // 监听器数据回填
    listenersDataReset(){
      const listeners = this?.businessObj?.listenerIds || "";
      const length = listeners && listeners.split(",").length || 0;
      this.form.items.listeners.options = length > 0 ? [{key: 1, label: length + "监听器"}] : [];
    },

    // 更新监听器数据到bpmn
    submitListeners(){
      const listenersData = this.$refs.listenersRef.listenersData;
      const validate = this.validateListenersData(listenersData);
      if(!validate) return;
      if (listenersData.length === 0) {
        this.modeler.updateProperties({
          listenerIds: undefined,
          extensionElements: undefined
        })
        this.visible = false;
        this.listenersDataReset();
        return;
      }
      const listeners = listenersData.map(item => {
        const listener = this.formatListenersList[item.listenerId];
        return {
          listenerType: getListenerType(listener),
          type: listener.type,
          eventName: item.eventId.join(","),
        }
      })
      this.modeler.updateExtensionElements(listeners);
      this.modeler.updateProperties({
        listenerIds: listenersData.map(item => item.listenerId).join(",")
      });
      this.visible = false;
      this.listenersDataReset();
      function getListenerType(data){
        const listenerTypes = ["expression", "delegateExpression", "clazz"];
        for(let i = 0, l = listenerTypes.length; i < l; i++){
          const type = listenerTypes[i];
          if(data[type]){
            return {
              type: type === "clazz" ? "class" : type,
              name: data[type]
            }
          }
        }
        return null
      }
    },

    validateListenersData(data){
      for(let i = 0, l = data.length; i < l; i++){
        if(data[i].eventId === "" || data[i].listenerId === ""){
          this.$message.error("监听器信息不完整，请完善");
          return false;
        }
      }
      return true;
    }
  },
}
</script>